package Pet.Management.repository;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import Pet.Management.domain.entity.Post;

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
    
    /**
     * 查询未删除的帖子列表
     */
    @Query("SELECT p FROM Post p WHERE p.delFlag = false ORDER BY p.createTime DESC")
    Page<Post> findLatestPosts(Pageable pageable);
    
    /**
     * 查询热门帖子
     */
    @Query("SELECT p FROM Post p WHERE p.delFlag = false ORDER BY p.likeCount DESC, p.commentCount DESC, p.viewCount DESC")
    Page<Post> findHottestPosts(Pageable pageable);
    
    /**
     * 根据标题和内容模糊搜索帖子
     */
    @Query("SELECT p FROM Post p WHERE p.delFlag = false AND (p.title LIKE %:keyword% OR p.content LIKE %:keyword%)")
    Page<Post> searchPosts(@Param("keyword") String keyword, Pageable pageable);
    
    /**
     * 查询指定用户的帖子
     */
    @Query("SELECT p FROM Post p WHERE p.delFlag = false AND p.user.id = :userId")
    Page<Post> findByUserId(@Param("userId") Long userId, Pageable pageable);
    
    /**
     * 更新帖子浏览量
     */
    @Modifying
    @Query("UPDATE Post p SET p.viewCount = p.viewCount + 1 WHERE p.id = :postId")
    void incrementViewCount(@Param("postId") Long postId);
    
    /**
     * 更新帖子点赞数
     */
    @Modifying
    @Query("UPDATE Post p SET p.likeCount = p.likeCount + :delta WHERE p.id = :postId")
    void updateLikeCount(@Param("postId") Long postId, @Param("delta") int delta);
    
    /**
     * 更新帖子收藏数
     */
    @Modifying
    @Query("UPDATE Post p SET p.favoriteCount = p.favoriteCount + :delta WHERE p.id = :postId")
    void updateFavoriteCount(@Param("postId") Long postId, @Param("delta") int delta);
    
    /**
     * 更新帖子评论数
     */
    @Modifying
    @Query("UPDATE Post p SET p.commentCount = p.commentCount + :delta WHERE p.id = :postId")
    void updateCommentCount(@Param("postId") Long postId, @Param("delta") int delta);

    /**
     * 根据用户ID和状态查询帖子
     */
    @Query("SELECT p FROM Post p WHERE p.delFlag = false AND p.user.id = :userId AND (:status IS NULL OR p.status = :status) ORDER BY p.createTime DESC")
    Page<Post> findByUserIdAndStatus(@Param("userId") Long userId, @Param("status") String status, Pageable pageable);
} 